package repositories

import (
	"gcopyright/models"
	"strconv"
	"time"
)

func (r *RepositoriesSqlite) CreatBalanceTable() {
	sql := r.sqlite
	sqlStmt := `
	create table balance_table (account text , object text ,balance text,date text,Timestamp text ,value text);
	`
	_, err := sql.Exec(sqlStmt)
	checkErr(err)
}

func (r *RepositoriesSqlite) InsertBalanceTable() {
	sql := r.sqlite
	stmt, err := sql.Prepare("INSERT INTO balance_table(account, object , balance,date,value,Timestamp) values(?,?,?,?,?,?)")
	checkErr(err)
	var result = models.BalanceTable{
		Account:   "0x09d3146906c7f39347dd977d303ad36e2a1186f6",
		Object:    "0x0000000000000000000000000000000000000000",
		Balance:   "1000",
		Data:      "20190729",
		Value:     "100",
		Timestamp: time.Now().String(),
	}
	res, err := stmt.Exec(&result.Account, &result.Object, &result.Balance, &result.Data, &result.Value, &result.Timestamp)
	checkErr(err)
	_, err = res.LastInsertId()
	checkErr(err)
}

func (r *RepositoriesSqlite) QuernAccountBalanceFor7(account string) []int {
	sql := r.sqlite
	rows, err := sql.Query("SELECT * FROM balance_table WHERE account = ?", account)
	checkErr(err)
	var result = models.BalanceTable{}
	var array = make([]models.BalanceTable, 0)
	var Balance7 = make([]int, 0)
	for rows.Next() {
		err = rows.Scan(&result.Account, &result.Object, &result.Balance, &result.Data, &result.Value, &result.Timestamp)
		array = append(array, result)
		checkErr(err)
	}
	array = array[len(array)-7:]
	for _, v := range array {
		temp, err := strconv.Atoi(v.Balance)
		checkErr(err)
		Balance7 = append(Balance7, temp)
	}
	return Balance7
}
